//
//  XMN_ DistrictViewController.m
//  B段项目
//
//  Created by dllo on 15/11/3.
//  Copyright © 2015年 谢美娜. All rights reserved.
//

#import "XMN_ DistrictViewController.h"
#import "XMN_Posts.h"
#import "XMN_PostImageCell.h"
#import "XMN_PostsCell.h"
#import "XMN_GroupCell.h"
#import "XMN_PostsViewController.h"
#import "XMN_GroupTopViewController.h"

@interface XMN__DistrictViewController ()<UITableViewDataSource, UITableViewDelegate, XMN_GroupCellDelegate>
@property(nonatomic, strong)UISegmentedControl *segmented;
@property(nonatomic, strong)myView *postsView;
@property(nonatomic, strong)myView *groupView;
@property(nonatomic, strong)NSMutableArray *postsArray;
@property(nonatomic, strong)NSMutableArray *groupArray;
@property(nonatomic, strong)UITableView *postsTableView;
@property(nonatomic, strong)UITableView *groupTableView;
@property(nonatomic, strong)myButton *hotButton;
@property(nonatomic, strong)UILabel *hotlabel;
@property(nonatomic, strong)UILabel *newestlabel;
@property(nonatomic, strong)myButton *newestButton;

@property(nonatomic, strong)NSString *pstr;
@property(nonatomic, strong)NSString *gstr;

@property(nonatomic, assign)NSInteger postsStart;
@property(nonatomic, assign)NSInteger groupStart;

@property(nonatomic, assign)NSInteger index;
@property(nonatomic, strong)XMN_ProgressHUD *HUD;
@end

@implementation XMN__DistrictViewController

-(void)loadView{
    [super loadView];
    
    //初始化数组
    _postsArray = [NSMutableArray array];
    _groupArray = [NSMutableArray array];
    _pstr = @"hot";
    _gstr = @"hot";
    
//    [self getGroupDataByUrlString];
//    [self getPostsDataByUrlSytring];
    
    //初始化View
    _postsView = [[myView alloc]initWithFrame:CGRectMake(0, 41 * FitHeight, ScreenWidth, Height - 41 * FitHeight)];
    [self.view addSubview:_postsView];
    _postsView.backgroundColor = [UIColor redColor];
    _groupView = [[myView alloc]initWithFrame:CGRectMake(ScreenWidth, 41 * FitHeight, ScreenWidth, Height - 41 * FitHeight)];
    _groupView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:_groupView];
    
    //初始化tableView
    _postsTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, Height - 41 * FitHeight) style:UITableViewStylePlain];
    _postsTableView.delegate = self;
    _postsTableView.dataSource = self;
    [_postsTableView NightWithType:UIViewColorType2];
    [_postsView addSubview:_postsTableView];
    
    _groupTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, Height - 41 * FitHeight) style:UITableViewStylePlain];
    _groupTableView.delegate = self;
    _groupTableView.dataSource = self;
    [_groupTableView NightWithType:UIViewColorType2];
    [_groupView addSubview:_groupTableView];
    
    
    //初始化button
    _hotButton = [myButton buttonWithType:UIButtonTypeSystem];
    _hotButton.frame = CGRectMake(0, 0, ScreenWidth / 2.0, 40 * FitHeight);
    [_hotButton setTitle:@"最热" forState:UIControlStateNormal];
    [self.view addSubview:_hotButton];
    _hotlabel = [[UILabel alloc]initWithFrame:CGRectMake(0, _hotButton.frame.size.height, _hotButton.frame.size.width, 1 * FitHeight)];
    _hotlabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_hotlabel];
    
    _newestButton = [myButton buttonWithType:UIButtonTypeSystem];
    _newestButton.frame = CGRectMake(_hotButton.frame.size.width, 0, _hotButton.frame.size.width, _hotButton.frame.size.height);
    [_newestButton setTitle:@"最新" forState:UIControlStateNormal];
    [self.view addSubview:_newestButton];
    _newestlabel = [[UILabel alloc]initWithFrame:CGRectMake(_newestButton.frame.origin.x, _newestButton.frame.size.height, _newestButton.frame.size.width, 1 * FitHeight)];
    _newestlabel.backgroundColor = [UIColor grayColor];
    _newestlabel.alpha = 0;
    [self.view addSubview:_newestlabel];
    
    [_hotButton addTarget:self action:@selector(postsHotbuttonAction) forControlEvents:UIControlEventTouchUpInside];
    [_newestButton addTarget:self action:@selector(postsNewestButtonAction) forControlEvents:UIControlEventTouchUpInside];

    
    _HUD = [[XMN_ProgressHUD alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, Height)];
    _HUD.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
    _HUD.XMN_label.text = @"Waiting...";
    [self.view addSubview:_HUD];
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    _postsTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        if (_postsArray.count != 0) {
//            [_postsArray removeAllObjects];
//        }
//        _postsStart = 0;
//        [self getPostsDataByUrlSytring];
//    }];
//    
//    _postsTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        _postsStart++;
//        [self getPostsDataByUrlSytring];
//    }];
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(getPostsDataByUrlSytring)];
    _postsTableView.header = header;
    NSMutableArray *array = [NSMutableArray array];
    for (NSInteger i = 1; i <= 9; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%lda", i]];
        [array addObject:image];
    }
    [header setImages:array duration:1 forState:MJRefreshStatePulling];
    header.lastUpdatedTimeLabel.hidden = YES;
    [header setTitle:@"加载中 ..." forState:MJRefreshStateRefreshing];
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(getPostsDataByUrlSytring)];
    _postsTableView.footer = footer;
    [footer setImages:array duration:1 forState:MJRefreshStateRefreshing];
    [_postsTableView.header beginRefreshing];

    
//    _groupTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        if (_groupArray.count != 0) {
//            [_groupArray removeAllObjects];
//        }
//        _groupStart = 0;
//        [self getGroupDataByUrlString];
//    }];
//    
//    _groupTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        _groupStart++;
//        [self getGroupDataByUrlString];
//    }];
    MJRefreshGifHeader *groupHeader = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(getGroupDataByUrlString)];
    _groupTableView.header = groupHeader;
    NSMutableArray *array2 = [NSMutableArray array];
    for (NSInteger i = 1; i <= 9; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%lda", i]];
        [array2 addObject:image];
    }
    [groupHeader setImages:array2 duration:1 forState:MJRefreshStatePulling];
    groupHeader.lastUpdatedTimeLabel.hidden = YES;
    [groupHeader setTitle:@"加载中 ..." forState:MJRefreshStateRefreshing];
    MJRefreshAutoGifFooter *groupFooter = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(getGroupDataByUrlString)];
    _groupTableView.footer = groupFooter;
    [groupFooter setImages:array2 duration:1 forState:MJRefreshStateRefreshing];
    [_groupTableView.header beginRefreshing];

}

-(void)segmentedControlAction:(UISegmentedControl *)segmented{
    switch (segmented.selectedSegmentIndex) {
        case 0:{
            [_postsTableView.header beginRefreshing];
            [UIView animateWithDuration:.5 animations:^{
                _postsView.frame = CGRectMake(0, 41 * FitHeight, ScreenWidth, Height - 41 * FitHeight);
                _groupView.frame = CGRectMake(ScreenWidth, 41 *FitHeight, ScreenWidth, Height - 41 * FitHeight);
            }];
            if ([_pstr isEqualToString:@"hot"]) {
                [UIView animateWithDuration:.8 animations:^{
                    _hotlabel.alpha = 1;
                    _newestlabel.alpha = 0;
                }];
            }else{
                [UIView animateWithDuration:.8 animations:^{
                    _hotlabel.alpha = 0;
                    _newestlabel.alpha = 1;
                }];
            }
            [_hotButton addTarget:self action:@selector(postsHotbuttonAction) forControlEvents:UIControlEventTouchUpInside];
            [_newestButton addTarget:self action:@selector(postsNewestButtonAction) forControlEvents:UIControlEventTouchUpInside];
            break;
        }
        case 1:{
            [_groupTableView.header beginRefreshing];
            [UIView animateWithDuration:.5 animations:^{
                _postsView.frame = CGRectMake(-ScreenWidth, 41 * FitHeight, ScreenWidth, Height - 41 * FitHeight);
                _groupView.frame = CGRectMake(0, 41 * FitHeight, ScreenWidth, Height - 41 * FitHeight);
            }];
            if ([_gstr isEqualToString:@"hot"]) {
                [UIView animateWithDuration:.8 animations:^{
                    _hotlabel.alpha = 1;
                    _newestlabel.alpha = 0;
                }];
            }else{
                [UIView animateWithDuration:.8 animations:^{
                    _hotlabel.alpha = 0;
                    _newestlabel.alpha = 1;
                }];
            }
            [_hotButton addTarget:self action:@selector(groupHotButtonAction) forControlEvents:UIControlEventTouchUpInside];
            [_newestButton addTarget:self action:@selector(groupNewestButtonAction) forControlEvents:UIControlEventTouchUpInside];
            break;
        }
            
        default:
            break;
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [_segmented removeFromSuperview];
}

-(void)viewWillAppear:(BOOL)animated{
    _segmented = [[UISegmentedControl alloc]initWithItems:@[@"话题", @"小组"]];
    _segmented.frame = CGRectMake((ScreenWidth - 140 * FitWidth) / 2.0, 14, 140 * FitWidth, 25);
    _segmented.tintColor = [UIColor whiteColor];
    [_segmented addTarget:self action:@selector(segmentedControlAction:) forControlEvents:UIControlEventValueChanged];
    [self.navigationController.navigationBar addSubview:_segmented];
}

#pragma mark - button点击事件
-(void)postsHotbuttonAction{
    [_postsTableView.header beginRefreshing];
    [UIView animateWithDuration:.8 animations:^{
        _hotlabel.alpha = 1;
        _newestlabel.alpha = 0;
    }];
    _pstr = @"hot";
}

-(void)postsNewestButtonAction{
    [_postsTableView.header beginRefreshing];
    [UIView animateWithDuration:.8 animations:^{
        _hotlabel.alpha = 0;
        _newestlabel.alpha = 1;
    }];
    _pstr = @"addtime";
}

-(void)groupHotButtonAction{
    [_groupTableView.header beginRefreshing];
    [UIView animateWithDuration:.8 animations:^{
        _hotlabel.alpha = 1;
        _newestlabel.alpha = 0;
    }];
    _gstr = @"hot";
}

-(void)groupNewestButtonAction{
    [_groupTableView.header beginRefreshing];
    [UIView animateWithDuration:.8 animations:^{
        _hotlabel.alpha = 0;
        _newestlabel.alpha = 1;
    }];
    _gstr = @"addtime";
}

#pragma mark - tableView相关设置
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _postsTableView) {
        return _postsArray.count;
    }
    return _groupArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_postsArray.count != 0) {
        if (tableView == _postsTableView) {
            XMN_Posts *posts = [_postsArray objectAtIndex:indexPath.row];
            if ([posts.coverimg isEqualToString:@""]) {
                static NSString *identifier = @"postsCell";
                XMN_PostsCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
                if (!cell) {
                    cell = [[XMN_PostsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                }
                cell.posts = posts;
                cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
                [UIView animateWithDuration:0.5 animations:^{
                    cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
                }];
                return cell;
            }
            static NSString *identifier = @"postsImageCell";
            XMN_PostImageCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[XMN_PostImageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            }
            cell.posts = posts;
            cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
            [UIView animateWithDuration:0.5 animations:^{
                cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
            }];
            return cell;
        }
    }
    static NSString *identifier = @"groupCell";
    XMN_GroupCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[XMN_GroupCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    if (_groupArray.count == 0) {
        return cell;
    }
    cell.group = [_groupArray objectAtIndex:indexPath.row];
    cell.delegate = self;
    cell.indexPath = indexPath;
    cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
    [UIView animateWithDuration:0.5 animations:^{
        cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
    }];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _postsTableView) {
        return 165 * FitHeight;
    }
    return 165 * FitHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _postsTableView) {
        XMN_PostsViewController *postsVC = [[XMN_PostsViewController alloc]init];
        [self.navigationController pushViewController:postsVC animated:YES];
        postsVC.titleString = [[_postsArray objectAtIndex:indexPath.row] title];
        postsVC.idString = [[_postsArray objectAtIndex:indexPath.row] contentid];
        postsVC.contentString = [[_postsArray objectAtIndex:indexPath.row] content];
    }
}

#pragma mark - 数据解析
-(void)getPostsDataByUrlSytring{
    if ([_postsTableView.header isRefreshing]) {
        _postsStart = 0;
        if (_postsArray.count != 0) {
            [_postsArray removeAllObjects];
        }

    }
    else{
        _postsStart ++;
    }
    [HTTPMethod getDataByString:@"http://api2.pianke.me/group/posts_hotlist" BODYDic:[ChangeString changeStringToDictionary:[NSString stringWithFormat:@"sort=%@&start=%ld&client=2&auth=W8A7Rym2z8m3lDC8hwH8XikTJxQMCqYOXe8zo6Wj0xcWP22NBKTh5Z7Pg&limit=10", _pstr, _postsStart * 10]] WithDataBlock:^(id data) {
        NSArray *array = [[data objectForKey:@"data"] objectForKey:@"list"];
        for (NSDictionary *dic in array) {
            XMN_Posts *posts = [[XMN_Posts alloc]init];
            [posts setValuesForKeysWithDictionary:dic];
            [_postsArray addObject:posts];
        }
        [_postsTableView.header endRefreshing];
        [_postsTableView.footer endRefreshing];
        [_postsTableView reloadData];
        [_HUD removeFromSuperview];
    }];
}

-(void)getGroupDataByUrlString{
    if ([_groupTableView.header isRefreshing]){
        _groupStart = 0;
        if (_groupArray.count != 0) {
            [_groupArray removeAllObjects];
        }
    }else{
        _groupStart ++;
    }
    [HTTPMethod getDataByString:@"http://api2.pianke.me/group/group_list" BODYDic:[ChangeString changeStringToDictionary:[NSString stringWithFormat:@"sort=%@&start=%ld&client=2&auth=W8A7Rym2z8m3lDC8hwH8XikTJxQMCqYOXe8zo6Wj0xcWP22NBKTh5Z7Pg&limit=10", _gstr, _groupStart * 10]] WithDataBlock:^(id data) {
        NSArray *array = [[data objectForKey:@"data"] objectForKey:@"list"];
        for (NSDictionary *dic in array) {
            XMN_Group *group = [[XMN_Group alloc]init];
            [group setValuesForKeysWithDictionary:dic];
            [_groupArray addObject:group];
        }
        [_groupTableView.header endRefreshing];
        [_groupTableView.footer endRefreshing];
        [_groupTableView reloadData];
        [_HUD removeFromSuperview];
    }];
}

#pragma mark - 代理方法
-(void)delegatePushAction:(NSIndexPath *)indexPath{
    XMN_GroupTopViewController *groupTopVc = [[XMN_GroupTopViewController alloc]init];
    [self.navigationController pushViewController:groupTopVc animated:YES];
    groupTopVc.group = [_groupArray objectAtIndex:indexPath.row];
}

-(void)delegateImageViewPushAction:(NSIndexPath *)indexPath :(NSInteger)index{
    XMN_PostsViewController *postsVC = [[XMN_PostsViewController alloc]init];
    [self.navigationController pushViewController:postsVC animated:YES];
    postsVC.idString = [[[[_groupArray objectAtIndex:indexPath.row] latestposts] objectAtIndex:index] objectForKey:@"contentid"];
    postsVC.titleString = [[[[_groupArray objectAtIndex:indexPath.row] latestposts] objectAtIndex:index] objectForKey:@"title"];
    postsVC.contentString = [[[[_groupArray objectAtIndex:indexPath.row] latestposts] objectAtIndex:index] objectForKey:@"content"];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
